#!/usr/bin/env python
# coding=utf-8

import re
from vavava import util
from datetime import datetime
from .. import fetcherbase,track_db

class FetcherTntInter(fetcherbase.FetcherBase):
    def __init__( self, item_id, log ):
        fetcherbase.FetcherBase.__init__(self, item_id=item_id, track_type=fetcherbase.TRACK_TYPE_TNT_INTER,log=log)
        self.post_url     = r'http://www.tnt.com/webtracker/tracking.do'
        self.page_referer = r'http://www.tnt.com/webtracker/tracker.do?navigation=1&respLang=en&respCountry=bw'
        self.post_data     = {
            "cons"             : item_id,
            "trackType"        : "CON",
            "genericSiteIdent" : ""   ,
            "page"             : "1"  ,
            "respLang"         : "en" ,
            "respCountry"      : "bw" ,
            "sourceID"         : "1"  ,
            "sourceCountry"    : "ww" ,
            "plazakey"         : ""   ,
            "refs"             : item_id,
            "requestType"      : "GEN",
            "searchType"       : "CON",
            "navigation"       : "1"
        }

        self.charset_1     = r"utf-8"
        self.reg_str       = r'<tr[^>]*>\s*' \
                             r'<td[^>]*>(?P<date>\d{2}\s+\w+\s+\d{4})[^<]*</td>\s*' \
                             r'<td[^>]*>(?P<time>\d{2}:\d{2}:\d{2})[^<]*</td>\s*' \
                             r'<td[^>]*>(?P<location>[^<]*)</td>\s*' \
                             r'<td[^>]*>(?P<desc>[^<]*)</td>\s*</tr>'
        self.date_format   = r'%d %b %Y %H:%M:%f'  # 19 Nov 2012 09:05:07

    def _fetch(self):
        result_list = []
        html_data = self.http.Post(self.post_url,self.post_data)
        html = html_data.decode(self.charset_1)
        item_infos = util.reg_helper(html,self.reg_str,re.I|re.S)
        # get item info list from tags
        if len(item_infos) > 0:
            for item_info in item_infos:
                time_str = datetime.strptime( item_info[0]+ " " + item_info[1], self.date_format )  # 19 Nov 2012 09:05:07
                item = track_db.TrackData.GetInstance(
                    [
                        -1,
                        self.track_type,
                        self.item_id,
                        time_str,
                        item_info[3].replace('\n\r\t','').replace('\r','').replace('\t', '').strip(),
                        item_info[2].replace('\n\r\t','').replace('\r','').replace('\t', '').strip(),
                        -1,
                        None
                    ]
                )
                if 'delivered' in item.description.lower():
                    item.is_ended = 1
                result_list.append(item)

        self._chk_new_items(result_list)

